//
//  SQLiteManager.m
//  SQLite
//
//  Created by ZX on 2017/6/27.
//  Copyright © 2017年 ZX. All rights reserved.
//

#import "SQLiteManager.h"
#import <FMDB.h>

@implementation SQLiteManager
//定义一个全局对象
static FMDatabase *_db;

//该方法会在调用该类中方法的时候先调用
+ (void)initialize{
    NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    
    NSString *dbFilePath = [documentPath stringByAppendingPathComponent:@"homeData.db"];
    NSLog(@"dbFilePath=%@",dbFilePath);
    //1.创建库
    _db = [FMDatabase databaseWithPath:dbFilePath];
    
    //2.打开连接
    BOOL result = [_db open];
    
    if (result) {
        //3.创建表
        /**
         如果是创建表,新增数据,修改数据,删除数据,我们都一个方法
         executeUpdate
         如果是查询executeQuery
         */
        BOOL result2 = [_db executeUpdate:@"create table if not exists t_home(id integer primary key,data text not null,page integer not null);"];
        if (result2) {
            NSLog(@"创建表成功!!!");
        }
    }
    
}

//添加数据
+ (void)insertHomeData:(NSString *)data page:(NSUInteger)page{
    [_db executeUpdateWithFormat:@"insert into t_home(data,page) values(%@,%ld)",data,page];
}

//更新数据
+ (void)updateHomeData:(NSString *)data page:(NSUInteger)page{
    [_db executeUpdateWithFormat:@"update t_home set data=%@,page = %ld",data,page];
}

//删除数据
+ (void)deleteHomeDataWithPage:(NSInteger)page{
    [_db executeUpdateWithFormat:@"delete from t_home where page = %ld",page];
}
//查询数据
+ (NSArray *)queryHomeData{
    
    FMResultSet *resultSet = [_db executeQuery:[NSString stringWithFormat:@"select * from t_home"]];
    // 如果你想查询某个字段可以这么写(注意%号的个数)
    //    FMResultSet *resultSet = [_db executeQuery:[NSString stringWithFormat:@"select * from t_home where name LIKE '%%%@%%'",str]];
    NSMutableArray *homeDatas = [NSMutableArray array];
    
    while (resultSet.next) {
        NSString *homeData = [resultSet stringForColumn:@"data"];
        // 将字符串转换成对象(下面会说为什么存字符串!!!)
        NSData *data = [homeData dataUsingEncoding:NSUTF8StringEncoding];
        NSArray *array = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:NULL];
        //将其添加到数组中
        [homeDatas addObject:array];
    }
    return homeDatas.copy;
}
@end
